<template>
  <l-layout class="l-tab-page" :left="208" v-show="!lr_loadPage">
    <template #left>
      <l-panel style="padding-right: 0">
        <template #title>
          {{ $t("数据库") }}
          <div class="tree-setting-btn">
            <el-tooltip effect="dark" content="数据库管理" placement="top">
              <el-button @click="handleSettingClick" type="text" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </div>
        </template>
        <el-tree v-loading="treeLoading" :data="lr_dblinkTree" :default-expand-all="true" @node-click="handleNodeClick">
          <span class="lr-tree-node" slot-scope="{ node, data }">
            <i v-if="data.icon" :class="data.icon"></i>
            {{ $t(node.label) }}
          </span>
        </el-tree>
      </l-panel>
    </template>
    <l-panel style="padding-left: 0">
      <template #toolLeft>
        <div class="l-panel--item">
          <el-input
            :placeholder="$t('请输入要查询关键字')"
            @keyup.enter.native="hanleSearch"
            v-model="searchWord"
            size="mini"
          >
            <el-button @click="hanleSearch" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>
      </template>
      <template #toolRight>
        <l-tool-btns :hasAdd="true" @click="handleAdd()">
          <el-button-group>
            <el-button size="mini" @click="handleOpenImport()"> 导入表 </el-button>
          </el-button-group>
        </l-tool-btns>
      </template>
      <l-table
        ref="mainTable"
        row-key="f_Id"
        :columns="columns"
        :dataSource="tableData"
        :loading="tableLoading"
        :isPage="true"
        :pageTotal="tableTotal"
        :tablePage.sync="tableCurrentPage"
        :isExpand="true"
        @loadPageData="turnTablePage"
        @expandChange="expandChange"
      >
        <template v-slot:table_expand="scope">
          <l-table :isChild="true" :columns="childColumns" :dataSource="chlidrenData[scope.row.f_TableName]">
            <template v-slot:f_IsNullable="scope">
              <el-switch size="mini" :activeValue="0" :inactiveValue="1" disabled v-model="scope.row.f_IsNullable">
              </el-switch>
            </template>
            <template v-slot:f_IsPrimaryKey="scope">
              <el-switch size="mini" :activeValue="1" :inactiveValue="0" disabled v-model="scope.row.f_IsPrimaryKey">
              </el-switch>
            </template>
            <template v-slot:f_IsIdentity="scope">
              <el-switch size="mini" :activeValue="1" :inactiveValue="0" disabled v-model="scope.row.f_IsIdentity">
              </el-switch>
            </template>
          </l-table>
        </template>

        <template v-slot:f_State="scope">
          <el-tag v-if="scope.row.f_State == 1" size="mini" type="success">同步</el-tag>
          <el-tag v-else size="mini" type="danger">未同步</el-tag>
        </template>

        <l-table-btns :btns="tableBtns" :isFixed="false" @click="lr_handleTableBtnClick"> </l-table-btns>
      </l-table>
    </l-panel>

    <!-- 导入虚拟类 -->
    <l-dbtable-selectdialog
      :visible.sync="dbTableVisible"
      :dbCode="this.dbCode"
      :isOkClose="false"
      @select="dbTableSelect"
    >
    </l-dbtable-selectdialog>

    <!--表单-->
    <l-dialog
      ref="dialogForm"
      :title="$t(formTitle)"
      :visible.sync="formVisible"
      :height="600"
      :width="1024"
      @ok="handleSave"
      @close="handleCloseForm"
      @opened="handleOpenedForm"
    >
      <my-form ref="form"></my-form>
      <template #btns>
        <el-button-group style="margin-right: 8px">
          <el-button plain type="primary" size="mini" icon="el-icon-plus" @click="handleAddRow">{{
            $t("添加字段")
          }}</el-button>
          <el-button plain type="primary" size="mini" icon="el-icon-s-unfold" @click="handleInsertRow">{{
            $t("插入字段")
          }}</el-button>
          <el-button plain type="primary" size="mini" icon="el-icon-minus" @click="handleDeleteRows">{{
            $t("删除字段")
          }}</el-button>
        </el-button-group>
        <el-button size="mini" @click="handleClose">{{ $t("取消") }}</el-button>
        <el-button size="mini" type="primary" @click="handleOk">{{ $t("确定") }}</el-button>
      </template>
    </l-dialog>

    <!--数据库管理-->
    <l-drawer
      :title="$t('数据库管理')"
      :visible.sync="dbManagerVisible"
      :showOk="false"
      :showClose="false"
      size="800px"
    >
      <dblink-index></dblink-index>
    </l-drawer>
  </l-layout>
</template>

<script>
const api = window.$api.data.codeTable;

import DblinkIndex from "../dblink/index";
import MyForm from "./form";
export default {
  components: {
    MyForm,
    DblinkIndex,
  },
  data() {
    return {
      lr_isPage: true,

      treeLoading: false,
      dbManagerVisible: false,

      //查询
      searchWord: "",

      dbCode: null,
      dbName: "",

      dbTableVisible: false,

      tableTotal: 0,
      tablePageSize: 50,
      tableCurrentPage: 1,
      tableLoading: false,
      tableData: [],
      columns: [
        { label: "表名", prop: "f_TableName", minWidth: 200 },
        { label: "备注", prop: "f_Description", minWidth: 200 },
        { label: "状态", prop: "f_State", width: 80, align: "center" },
      ],
      childColumns: [
        { prop: "f_DbColumnName", label: "名称", minWidth: 120 },
        { prop: "f_CsType", label: "类型", width: 120 },
        { prop: "f_Length", label: "长度", width: 80 },
        { prop: "f_DecimalDigits", label: "小数位", width: 64 },
        { prop: "f_IsNullable", label: "必填", width: 64, align: "center" },
        { prop: "f_IsPrimaryKey", label: "主键", width: 64, align: "center" },
        { prop: "f_IsIdentity", label: "自增", width: 64, align: "center" },
        { prop: "f_Description", label: "备注", minWidth: 120 },
      ],
      tableBtns: [
        { prop: "Edit", label: "编辑" },
        { prop: "UpdateTable", label: "更新表", width: 64 },
        { prop: "Delete", label: "删除" },
      ],

      // 表单参数
      formTitle: "",
      formVisible: false,
      formEditRow: null,
      formEdit: false,

      //
      chlidrenData: {},
    };
  },
  mounted() {
    this.initDbLink();
  },
  methods: {
    // 数据库连接
    async initDbLink() {
      this.treeLoading = true;
      await this.lr_loadDblink(false);
      this.treeLoading = false;
    },
    handleNodeClick(data) {
      if (!data.children) {
        if (this.dbCode != data.id) {
          this.dbCode = data.id;
          this.dbName = data.label;
          this.searchWord = "";
          this.chlidrenData = {};
          this.loadTableData();
        }
      } else {
        this.dbCode = "";
        this.dbName = "";
        this.searchWord = "";
        this.chlidrenData = {};
        this.tableData = [];
        this.tableTotal = 0;
      }
    },
    handleSettingClick() {
      this.dbManagerVisible = true;
    },

    hanleSearch() {
      this.loadTableData();
    },
    loadTableData(isNotFirst) {
      if (!isNotFirst) {
        this.tableCurrentPage = 1;
      }
      this.tableLoading = true;
      let queryData = {
        rows: this.tablePageSize,
        page: this.tableCurrentPage,
        sidx: "F_TableName DESC",
        keyWord: this.searchWord,
        dbCode: this.dbCode,
      };
      api
        .getPage(queryData)
        .then((res) => {
          const data = this.$deepClone(res.data.data);
          this.tableData = data.rows;
          this.tableTotal = data.records;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableData = [];
          this.tableTotal = 0;
          this.tableLoading = false;
        });
    },
    turnTablePage({ rows }) {
      this.tablePageSize = rows;
      this.loadTableData(true);
    },

    // 导入
    handleOpenImport() {
      if (this.$validatenull(this.dbCode)) {
        this.$message({
          type: "warning",
          message: "请选择数据库!",
        });
      } else {
        this.dbTableVisible = true;
      }
    },
    async dbTableSelect(list, showLoading, hideLoading) {
      showLoading();
      if (list.length == 0) {
        this.$message({
          type: "warning",
          message: "请选择一条数据!",
        });
        hideLoading();
      }
      const postData = {
        tableList: list,
      };

      const data = await this.$awaitWraper(api.importTable(this.dbCode, postData));
      if (data) {
        this.$message({
          type: "success",
          message: this.$t("导入成功!"),
        });
        this.loadTableData();
        this.dbTableVisible = false;
      }
      hideLoading();
    },

    //列表功能页-新增/编辑
    handleAdd() {
      if (this.dbCode == "0" || this.dbCode == null || this.dbCode == "") {
        this.$message({
          type: "warning",
          message: "请选择数据库!",
        });
      } else {
        this.formEdit = false;
        this.handleShowForm("新增数据对象");
      }
    },
    handleEdit($index, row) {
      this.formEdit = true;
      this.formEditRow = row;
      this.handleShowForm(`编辑数据对象-${row.f_TableName}`);
    },
    handleDelete($index, row) {
      this.$confirm(this.$t("此操作将永久删除该数据, 是否继续?"), this.$t("提示"), {
        confirmButtonText: this.$t("确定"),
        cancelButtonText: this.$t("取消"),
        type: "warning",
      })
        .then(async () => {
          await api.remove(row.f_Id);
          this.tableData.splice($index, 1);
          this.tableTotal--;
          this.$message({
            type: "success",
            message: this.$t("删除成功!"),
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("已取消删除!"),
          });
        });
    },

    handleClose() {
      this.formVisible = false;
    },

    handleShowForm(text) {
      this.formTitle = text;
      this.formVisible = true;
    },
    async handleOpenedForm(showLoading, hideLoading) {
      if (this.formEdit) {
        showLoading("加载数据中...");
        await this.$refs.form.loadFormData({ keyValue: this.formEditRow.f_Id });
        hideLoading();
      }
    },
    handleCloseForm() {
      this.$refs.form.resetForm();
    },

    handleOk() {
      this.$refs.dialogForm.handleOk();
    },
    handleAddRow() {
      this.$refs.form.handleAddRow();
    },
    handleInsertRow() {
      this.$refs.form.handleInsertRow();
    },
    handleDeleteRows() {
      this.$refs.form.handleDeleteRows();
    },

    async handleSave(showLoading, hideLoading) {
      showLoading("保存数据中...");
      if (await this.$refs.form.validateForm()) {
        const res = await this.$refs.form.saveForm({
          keyValue: this.formEdit ? this.formEditRow.f_Id : "",
          isEdit: this.formEdit,
          dbCode: this.dbCode,
        });

        const formData = this.$refs.form.getForm();
        if (this.chlidrenData[formData.lr_db_codetableEntity.f_TableName]) {
          this.chlidrenData[formData.lr_db_codetableEntity.f_TableName] = formData.lr_db_codecolumnsList;
        }

        if (res) {
          const msg = this.formEdit ? "更新成功!" : "新增成功!";
          this.$message({
            type: "success",
            message: this.$t(msg),
          });
          this.loadTableData();
          this.formVisible = false;
        }
      }
      hideLoading();
    },
    //更新数据库
    handleUpdateTable($index, row) {
      if (this.appConfig.online) {
        this.$message({
          type: "success",
          message: this.$t("体验版本无法对数据库新增和修改表!"),
        });
        return;
      }

      this.$confirm(this.$t("此操作将进行数据库更新, 是否继续?"), this.$t("提示"), {
        confirmButtonText: this.$t("确定"),
        cancelButtonText: this.$t("取消"),
        type: "warning",
      })
        .then(async () => {
          const loading = this.$loading({
            target: this.$refs.mainTable ? this.$refs.mainTable.$el : "document.body",
            lock: true,
            text: "更新数据表中...",
            spinner: "el-icon-loading",
          });
          const res = await this.$awaitWraper(api.createOrUpdateTable(row.f_Id, this.dbCode, this.dbName));
          if (res) {
            this.$message({
              type: "success",
              message: this.$t("更新成功!"),
            });
            this.loadTableData();
          }

          loading.close();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("已取消更新!"),
          });
        });
    },
    async expandChange(row) {
      if (!this.chlidrenData[row.f_TableName]) {
        const data = await this.$awaitWraper(api.get(row.f_Id));
        this.$set(this.chlidrenData, row.f_TableName, data.lr_db_codecolumnsList);
      }
    },
  },
};
</script>
